<template>
	<div>
    <zh-table
				ref="tableListRef"
				title="excel字段列表"
				:height="700"
        type="default"
        show-overflow
        keep-source
        :data="state.tableData"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
				:columns="state.tableColumn"
        :show-header-overflow="false"
        :column-config="{resizable: true}"
        :tree-config="{children: 'children', rowField: 'key', parentField: 'parentKey'}"
				:disabled="false"
        :scrollY="{enabled: false}"
        :stripe="false"
        :draggable="true"
        @row-drag-change="onChange"
        :rowConfig="{keyField:'id',useKey: true}"
				highlight-current-row
			>
        <template #key_edit="{ row }">
          <zh-input v-model="row.key"  @change="onChange"></zh-input>
        </template>
        <template #title_edit="{ row }">
          <zh-input v-model="row.title"  @change="onChange"></zh-input>
        </template>
        <template #decimalPlaces_edit="{ row }">
          <zh-number v-model="row.decimalPlaces"  @change="onChange"></zh-number>
        </template>
        <template #dictField_edit="{ row }">
          <zh-input v-model="row.dictField"  @change="onChange"></zh-input>
        </template>
        <template #width_edit="{ row }">
          <zh-number v-model="row.width"  @change="onChange"></zh-number>
        </template>
        <template #cellType_default="{ row }">
          {{row.cellTypeName}}
        </template>
        <template #cellType_edit="{ row }">
          <zh-ele-select v-model="row.cellType" @change="onCellTypeChange($event,row)" :options="state.dictData.cellType"></zh-ele-select>
        </template>
        <template #header_button>
          <zh-button button-type="add" v-func:excelModel0108 @click="addParam()">新增字段</zh-button>
        </template>
        <template #operate_default="{ row }">
          <el-tooltip
            effect="dark"
            content="下级插入字段"
            placement="top"
            
          >
            <zh-button v-func:excelModel0108 button-type="add" link @click="addChildParam(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="删除字段"
            placement="top"
            
          >
            <zh-button v-func:excelModel0108 type="danger" icon="ele-Minus" link @click="delParam(row)"></zh-button>
          </el-tooltip>
          
				</template>
			</zh-table>
  </div>
</template>
<script lang="ts" setup name="ExcelParamsFrom">
import { ElMessage } from 'element-plus';
import { uuid } from '@/utils/util';
//------------------接收传入参数(组件)-------------------
const props = defineProps({
	modelInfo: {
		type: Object,
		default: () => {},
		required: false,
	},
  modelValue: Boolean,
});
//------------------定义子组件---------------------------
const tableListRef=ref();
//------------------内部变量定义-------------------------
const state=reactive({
  tableData:[],
  canSave:false,
  insertList:[],
  dictData:{},
  tableColumn:[
    { field: 'key', title: '字段属性名', editRender:{},treeNode:'true',align: 'left', width: 200,slots: {edit: 'key_edit'} },
    { field: 'title', title: 'excel列名',  editRender:{}, align: 'center', width: 200,slots: {edit: 'title_edit'} },
    { field: 'width', title: '宽度', align: 'center', editRender:{},  width: 150,slots: {edit: 'width_edit'}},
    { field: 'cellType', title: '字段类型',  align: 'center', editRender:{}, width: 200,slots: {default:'cellType_default',edit: 'cellType_edit'} },
    { field: 'decimalPlaces', title: '小数点位数',  align: 'center', editRender:{}, width: 150,slots: {edit: 'decimalPlaces_edit'} },
    { field: 'dictField', title: '数据字典字段',  align: 'center', editRender:{}, width: 150,slots: {edit: 'dictField_edit'} },
    { field: 'operate', title: '操作', align: 'center',fixed: 'right',  width: 100,slots: {default: 'operate_default'}},
  ]
})
//------------------定义调用方法-------------------------
const onCellTypeChange=(val,row)=>{
  let dictList=state.dictData.cellType.filter(item => item.dictKey === val)
  if(dictList&&dictList.length>0){
    row.cellTypeName=dictList[0].dictValue
  }
  state.canSave=true
}
const onChange=()=>{
  state.canSave=true
}
const addParam=()=>{
  //新增
  let id=uuid()
  let params={id:id,parentKey:null,key:null,title:null,children:[]}
  let tableData=[...state.tableData]
  tableData.push(params)
  state.tableData=tableData
  state.insertList.push(id)
}
const addChildParam=(row)=>{
  //子级新增
  if(!row.key){
    ElMessage.error('字段属性为空，不能创建子节点');
    return;
  }
  let id=uuid()
  let params={id:id,parentKey:row.key}
  let children=row.children||[]
  children.push(params);
  row.children=children
  state.tableData=[...state.tableData]
  tableListRef.value.setTreeExpand(row, true)
  state.insertList.push(id)
}
const delParam=(row)=>{
  //删除字段
  let list=[...state.tableData]
  delParamByRow(row,list);
  state.tableData=list;
  let deleteIndex=state.insertList.indexOf(row.id);
  state.insertList.splice(deleteIndex, 1)
  if(deleteIndex<0){
    state.canSave=true;
  }
}
const delParamByRow=(row,list)=>{
  for (let i = 0, len = list.length; i < len; i++) {
    let item=list[i]
    if(item.id === row.id){
      list.splice(i, 1)
      break;
    }else{
      if(item.children&&item.children.length>0){
        delParamByRow(row,item.children)
      }
    }
  }
  
} 
const queryTable=()=>{
  //查询模版字段
  setTimeout(() => {
    let params={excelModelId:props.modelInfo.id}
		$api.common.send.post('excelModel0107', params).then((res) => {  
			state.tableData = res.result||[];
		});
	}, 20);
}
const isEdit=()=>{
  //判断是否做过信息变动
  let canSave=state.canSave;
  let updateList=tableListRef.value.getUpdateRecords();
  if(updateList&&updateList.length>0){
    canSave=true;
  }
  if(state.insertList.length>0){
    canSave=true;
  }
  return canSave;
}
const save=()=>{
  //保存方法
  if(!state.tableData||state.tableData.length<=0){
    ElMessage.error('数据为空，不能保存');
    return;
  }

  if(!isEdit()){
    ElMessage.error('没有字段信息变动，不能保存');
    return;
  }
  let list=tableListRef.value.getTableData().tableData
  let params={excelModelId:props.modelInfo.id,list:list}
	$api.common.send.post('excelModel0108', params).then(() => {  
    reset();
    ElMessage.success('保存成功！');
	});
}
const reset=()=>{
  //重置数据
  queryTable();
  state.canSave=false;
  state.insertList=[]
}
//------------------初始化------------------------------
onMounted(()=>{
  queryTable();
  initDict();
})
const initDict=()=>{
  const params = {
    dictFields: 'cellType',
  };
  $api.common.getBatchDict.post(params).then((res) => {
    state.dictData = res.result;
  });
}
//------------设置给父组件调用的数据/方法(组件)-----------
defineExpose({ form: state.form ,save,reset,isEdit});
</script>
<style lang="scss" scoped></style>
